#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdint.h>
#include <string>
#include <memory>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/wait.h>
#include "threadpool.hpp"

class Handler
{
public:
    Handler()
    {}
    ~Handler()
    {}

    void operator()(int sockfd,std::string client_ip,int client_port)
    {
char buffer[1024];
        while(true)
        {
            ssize_t size = read(sockfd,buffer,sizeof(buffer) - 1);
            if(size > 0)
            {
                buffer[size] = '\0';
                std::cout << "[" << client_ip << "]:" << buffer << std::endl;
                write(sockfd,buffer,size);
            }
            else if(size == 0)//对端关闭
            {
                std::cout << client_ip << ":" << client_port << " close!" << std::endl;
                break;
            }
            else
            {
                std::cout << "read error" << std::endl;
                break;
            }
        }
        close(sockfd);
        std::cout << client_ip << ":" << client_port << " service done!" << std::endl;
    }
};

class Task
{
public:
    Task()
    {}
    Task(int sockfd,std::string client_ip,int client_port)
        :_sockfd(sockfd)
        ,_client_ip(client_ip)
        ,_client_port(client_port)
    {

    }

    void Run()
    {
        _handler(_sockfd,_client_ip,_client_port);
    }
private:
    int _sockfd;
    std::string _client_ip;
    int _client_port;
    Handler _handler; //处理方法
};

const int BACKLOG = 5;
class TcpServer
{
public:
    TcpServer(int port)
        :_listen_sockfd(-1)
        ,_port(port)
        ,_tp(nullptr)
    {}

    void Start()
    {
        //线程池初始化
        _tp->ThreadPoolInit();
        //忽略SIGCHLD信号
        signal(SIGCHLD,SIG_IGN);
        while(true)
        {
            //获取连接 
            struct sockaddr_in peer;
            bzero(&peer,sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listen_sockfd,(struct sockaddr*)&peer,&len);
            if(sockfd < 0)
            {
                std::cout << "accept error,continue" << std::endl;
                continue;
            }

            std::string client_ip = inet_ntoa(peer.sin_addr);
            int client_port = ntohs(peer.sin_port);
            std::cout << "get a new link -> " << sockfd << "[" << client_ip << "]:" << client_port << std::endl;

            Task task(sockfd,client_ip,client_port);    //构造任务
            _tp->Push(task);                            //加入任务队列
        }
    }

    void InitServer()
    {
        //创建套接字
        _listen_sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sockfd < 0)
        {
            std::cout << "socket error" << std::endl;
            exit(2);
        }
        //绑定
        struct sockaddr_in local;
        memset(&local,'\0',sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if(bind(_listen_sockfd,(struct sockaddr*)&local,sizeof(local)) < 0)
        {
            std::cout << "bind error" << std::endl;
            exit(3);
        }
        //监听
        if(listen(_listen_sockfd,BACKLOG) < 0)
        {
            std::cout << "listen error" << std::endl;
            exit(4);
        }

        _tp = new ThreadPool<Task>(); //构造线程池对象
    }
    ~TcpServer()
    {
        if(_listen_sockfd >= 0)
        {
            close(_listen_sockfd);
        }
    }

private:
    int _listen_sockfd;//套接字
    int _port;//端口号
    ThreadPool<Task>* _tp;  //线程池
};